package com.slofzx.nuoda.evaluation.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.slofzx.nuoda.common.dto.PageDTO;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import com.slofzx.nuoda.common.util.IdGen;
import com.slofzx.nuoda.evaluation.project.dao.BatchCommonDataDAO;
import com.slofzx.nuoda.evaluation.project.dao.BatchInfoDAO;
import com.slofzx.nuoda.evaluation.project.dto.BatchCommonDataDTO;
import com.slofzx.nuoda.evaluation.project.dto.BatchCommonDataExcelDTO;
import com.slofzx.nuoda.evaluation.project.entity.BatchCommonData;
import com.slofzx.nuoda.evaluation.project.entity.BatchInfo;
import com.slofzx.nuoda.evaluation.project.enums.CostEvaMethodEnum;
import com.slofzx.nuoda.evaluation.project.observer.BatchObserver;
import com.slofzx.nuoda.evaluation.project.service.BatchCommonDataService;
import com.slofzx.nuoda.evaluation.project.vo.BatchCommonDataVO;
import com.slofzx.nuoda.excel.vo.ExcelPreviewDataVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 评价任务公共数据服务实现类
 *
 * @author nuoda
 * @since 2023-10-20 09:12:10
 */
@Service("batchCommonDataService")
public class BatchCommonDataServiceImpl extends BaseServiceImpl implements BatchCommonDataService, BatchObserver {

    @Resource
    private BatchCommonDataDAO batchCommonDataDAO;
    @Resource
    private BatchInfoDAO batchInfoDAO;

    /**
     * 将数据表数据转换为返回数据类型
     *
     * @param entity 数据表对应类
     * @return 实例对象
     */
    protected BatchCommonDataVO parseEntity2VO(BatchCommonData entity) {
        BatchCommonDataVO vo = new BatchCommonDataVO();
        vo.setId(entity.getId());
        vo.setBatchId(entity.getBatchId());
        vo.setYear(entity.getYear());
        vo.setOilPrice(entity.getOilPrice());
        vo.setGasPrice(entity.getGasPrice());
        vo.setCondensatePrice(entity.getCondensatePrice());
        vo.setLiquidGasPrice(entity.getLiquidGasPrice());
        vo.setOilCommodityRate(entity.getOilCommodityRate());
        vo.setGasCommodityRate(entity.getGasCommodityRate());
        vo.setOtherCommodityRate(entity.getOtherCommodityRate());
        vo.setCreateUser(entity.getCreateUser());
        vo.setCreateTime(entity.getCreateTime());
        return vo;
    }

    /**
     * 将数据传递类转换为数据表数据类
     *
     * @param dto 数据传递类实例
     * @return 实例对象
     */
    protected BatchCommonData parseDTO2Entity(BatchCommonDataDTO dto) {
        BatchCommonData entity = new BatchCommonData();
        entity.setId(dto.getId());
        entity.setBatchId(dto.getBatchId());
        entity.setYear(dto.getYear());
        entity.setOilPrice(dto.getOilPrice());
        entity.setGasPrice(dto.getGasPrice());
        entity.setCondensatePrice(dto.getCondensatePrice());
        entity.setLiquidGasPrice(dto.getLiquidGasPrice());
        entity.setOilCommodityRate(dto.getOilCommodityRate());
        entity.setGasCommodityRate(dto.getGasCommodityRate());
        entity.setOtherCommodityRate(dto.getOtherCommodityRate());
        return entity;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BatchCommonDataVO queryById(String id) {
        BatchCommonData entity = this.batchCommonDataDAO.selectById(id);
        if (entity == null) {
            return null;
        }
        return parseEntity2VO(entity);
    }

    /**
     * 查询多条数据
     *
     * @param dto 数据传递类实例对象
     * @return 对象列表
     */
    @Override
    public List<BatchCommonDataVO> queryList(BatchCommonDataDTO dto) {
        //mybatis-plus 写法示例
        //IPage<BatchCommonData> pageResult = this.evaModelDAO.selectPage(new Page<>(dto.getPageNo(),dto.getPageSize()),null);
        //List<BatchCommonData> dataList = pageResult.getRecords();
        //dto.setCount((int) pageResult.getTotal());
        List<BatchCommonData> dataList = this.batchCommonDataDAO.queryList(dto);
        if (null == dataList || dataList.isEmpty()) {
            return Collections.emptyList();
        }
        List<BatchCommonDataVO> resultList = new ArrayList(dataList.size());
        for (BatchCommonData item : dataList) {
            BatchCommonDataVO vo = parseEntity2VO(item);
            resultList.add(vo);
        }
        // TODO 添加其他关联查询数据
        return resultList;
    }

    /**
     * 新增数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult create(BatchCommonDataDTO dto) {
        // TODO 添加校验逻辑
        BatchCommonData entity = parseDTO2Entity(dto);
        preInsert(entity);
        this.batchCommonDataDAO.insert(entity);
        return CommonResultEnum.SUCCESS;
    }
    @Override
    public ServiceResult batchCreate(List<BatchCommonDataDTO> dtos) {
        final String userId = getUserId();
        List<BatchCommonData> commonDataList = new ArrayList<>();
        for (BatchCommonDataDTO dto : dtos) {
            BatchCommonData entity = parseDTO2Entity(dto);
            entity.setCreateTime(new Date());
            entity.setCreateUser(userId);
            entity.setId(IdGen.uuid());
        }
        saveBatch(commonDataList,batchCommonDataDAO,BatchCommonData.class);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 修改数据
     *
     * @param dto 实例对象
     * @return 操作结果
     */
    @Override
    public ServiceResult update(BatchCommonDataDTO dto) {
        String id = dto.getId();
        if (StringUtils.isEmpty(id)) {
            return CommonResultEnum.NOT_EXIST;
        }
        BatchCommonData entity = this.batchCommonDataDAO.selectById(id);
        if (entity == null) {
            return CommonResultEnum.NOT_EXIST;
        }
        // TODO 添加其他校验逻辑，如数据权限

        entity.setBatchId(dto.getBatchId());
        entity.setYear(dto.getYear());
        entity.setOilPrice(dto.getOilPrice());
        entity.setGasPrice(dto.getGasPrice());
        entity.setCondensatePrice(dto.getCondensatePrice());
        entity.setLiquidGasPrice(dto.getLiquidGasPrice());
        entity.setOilCommodityRate(dto.getOilCommodityRate());
        entity.setGasCommodityRate(dto.getGasCommodityRate());
        entity.setOtherCommodityRate(dto.getOtherCommodityRate());
        this.batchCommonDataDAO.updateById(entity);
        return CommonResultEnum.SUCCESS;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 操作结果
     */
    @Override
    public ServiceResult deleteById(String id) {
        // TODO 添加校验逻辑，如数据权限
        this.batchCommonDataDAO.deleteById(id);
        return CommonResultEnum.SUCCESS;
    }

    @Transactional
    public ServiceResult deleteByBatchId(String batchId) {
        if(StringUtils.isBlank(batchId)){
            return CommonResultEnum.VALUE_LOOSE;
        }
        LambdaQueryWrapper<BatchCommonData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BatchCommonData::getBatchId,batchId);
        batchCommonDataDAO.delete(queryWrapper);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    public ServiceResult importExcelData(String batchId, ExcelPreviewDataVO uploadFileData) {
//        if(StringUtils.isBlank(batchId) || uploadFileData == null ){
//            return CommonResultEnum.VALUE_LOOSE;
//        }
//        CostEvaMethodEnum costEvaMethodEnum = CostEvaMethodEnum.getEnumByName(costEvaMethod);
//        if(costEvaMethodEnum == null){
//            throw new ServiceException("操作失败，公共参数中的【成本测算方式】值不正确，请检查后重试",
//                    "公共参数中的【成本测算方式】值不正确 excelDataList:{}",excelDataList);
//        }
//
//        ServiceResult serviceResult = this.deleteByBatchId(batchId);
//        if(serviceResult != CommonResultEnum.SUCCESS){
//            return serviceResult;
//        }
//
//        LambdaUpdateWrapper<BatchInfo> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(BatchInfo::getId,batchId);
//        updateWrapper.set(BatchInfo::getCostEvaMethod,costEvaMethodEnum.getId());
//        batchInfoDAO.update(null,updateWrapper);
//
//        List<BatchCommonData> entityList = new ArrayList<>();
//        for (int i = 1; i < 21; i++) {
//            BatchCommonData entity = new BatchCommonData();
//            preInsert(entity);
//            entity.setBatchId(batchId);
//            entity.setYear(i);
//            for (int j = 0; j < excelDataList.size() ; j++) {
//                if(j == excelDataList.size() - 1){
//                    continue;
//                }
//                Double propertyValue = null;
//                BatchCommonDataExcelDTO importDTO = excelDataList.get(j);
//                String oriValue = null;
//                if( i == 1){
//                    oriValue = importDTO.getFirstYear();
//                }else if(i == 2){
//                    oriValue = importDTO.getSecondYear();
//                }else if(i == 3){
//                    oriValue = importDTO.getThirdYear();
//                }else if(i == 4){
//                    oriValue = importDTO.getFourthYear();
//                }else if(i == 5){
//                    oriValue = importDTO.getFifthYear();
//                }else if(i == 6){
//                    oriValue = importDTO.getSixthYear();
//                }else if(i == 7){
//                    oriValue = importDTO.getSeventhYear();
//                }else if(i == 8){
//                    oriValue = importDTO.getEighthYear();
//                }else if(i == 9){
//                    oriValue = importDTO.getNinthYear();
//                }else if(i == 10){
//                    oriValue = importDTO.getTenthYear();
//                }else if(i == 11){
//                    oriValue = importDTO.getEleventhYear();
//                }else if(i == 12){
//                    oriValue = importDTO.getTwelfthYear();
//                }else if(i == 13){
//                    oriValue = importDTO.getThirteenthYear();
//                }else if(i == 14){
//                    oriValue = importDTO.getFourteenthYear();
//                }else if(i == 15){
//                    oriValue = importDTO.getFifteenthYear();
//                }else if(i == 16){
//                    oriValue = importDTO.getSixteenthYear();
//                }else if(i == 17){
//                    oriValue = importDTO.getSeventeenthYear();
//                }else if(i == 18){
//                    oriValue = importDTO.getEighteenthYear();
//                }else if(i == 19){
//                    oriValue = importDTO.getNineteenthYear();
//                }else if(i == 20){
//                    oriValue = importDTO.getTwentiethYear();
//                }
//                try{
//                    if(StringUtils.isNotBlank(oriValue)){
//                        propertyValue = Double.valueOf(oriValue);
//                    }
//                }catch (Exception e){
//                    logger.error("导入数据异常（需要数字类型实际为非数字类型）");
//                }
//
//                if( j == 0){
//                    entity.setOilPrice(propertyValue);
//                }else if(j == 1){
//                    entity.setGasPrice(propertyValue);
//                }else if(j == 2){
//                    entity.setCondensatePrice(propertyValue);
//                }else if(j == 3){
//                    entity.setLiquidGasPrice(propertyValue);
//                }else if(j == 4){
//                    entity.setOilCommodityRate(propertyValue);
//                }else if(j == 5){
//                    entity.setGasCommodityRate(propertyValue);
//                }else if(j == 6){
//                    entity.setOtherCommodityRate(propertyValue);
//                }
//            }
//            entityList.add(entity);
//        }
//        batchCommonDataDAO.insertBatch(entityList);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    public ServiceResult batchInsertData(String batchId, List<BatchCommonDataDTO> batchCommonDTOList) {
        if(StringUtils.isBlank(batchId) || batchCommonDTOList == null || batchCommonDTOList.isEmpty()){
            return CommonResultEnum.VALUE_LOOSE;
        }
        this.deleteByBatchId(batchId);
        final String userId = getUserId();
        List<BatchCommonData> entityList = new ArrayList<>();
        for (BatchCommonDataDTO dto : batchCommonDTOList) {
            BatchCommonData entity = this.parseDTO2Entity(dto);
            entity.setCreateTime(new Date());
            entity.setId(IdGen.uuid());
            entity.setCreateUser(userId);
            entityList.add(entity);
        }
        batchCommonDataDAO.insertBatch(entityList);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    public List<BatchCommonDataExcelDTO> getExcelData(String batchId) {
        if(StringUtils.isBlank(batchId)){
            return Collections.emptyList();
        }
        BatchInfo batchInfo = batchInfoDAO.selectById(batchId);
        if(batchInfo == null){
            return Collections.emptyList();
        }
        BatchCommonDataDTO dto = new BatchCommonDataDTO();
        dto.setBatchId(batchId);
        dto.setPageSize(PageDTO.ALL);
        List<BatchCommonData> dataList = batchCommonDataDAO.queryList(dto);
        if(dataList == null || dataList.isEmpty()){
            return Collections.emptyList();
        }
        Map<Integer,BatchCommonData> dataMap = new HashMap<>();
        for (BatchCommonData entity : dataList) {
            dataMap.put(entity.getYear(),entity);
        }

        List<String> commonItemList = new ArrayList<>();
        commonItemList.add("原油价格（元/吨）");
        commonItemList.add("天然气价格（元/千方）");
        commonItemList.add("轻烃价格（元/吨）");
        commonItemList.add("液化气价格（元/吨）");
        commonItemList.add("原油商品率（%）");
        commonItemList.add("天然气商品率（%）");
        commonItemList.add("其他产品商品率（%）");
        commonItemList.add("成本测算方式");

        List<BatchCommonDataExcelDTO> resultList = new ArrayList<>();
        for (String type : commonItemList) {
            BatchCommonDataExcelDTO excelDTO = new BatchCommonDataExcelDTO();
            excelDTO.setType(type);
            if(type.equals("成本测算方式")){
                CostEvaMethodEnum costEvaMethodEnum = CostEvaMethodEnum.getEnum(batchInfo.getCostEvaMethod());
                excelDTO.setFirstYear(costEvaMethodEnum == null ? "" : costEvaMethodEnum.getName()); ;
            }else{
                for (int i = 1; i < 21; i++) {
                    BatchCommonData batchCommonData = dataMap.get(i);
                    if(batchCommonData == null){
                        continue;
                    }
                    String value = this.getExcelValue(type,batchCommonData);
                    if( i == 1){
                        excelDTO.setFirstYear(value);
                    }else if(i == 2){
                        excelDTO.setSecondYear(value);
                    }else if(i == 3){
                        excelDTO.setThirdYear(value);
                    }else if(i == 4){
                        excelDTO.setFourthYear(value);
                    }else if(i == 5){
                        excelDTO.setFifthYear(value);
                    }else if(i == 6){
                        excelDTO.setSixthYear(value);
                    }else if(i == 7){
                        excelDTO.setSeventhYear(value);
                    }else if(i == 8){
                        excelDTO.setEighthYear(value);
                    }else if(i == 9){
                        excelDTO.setNinthYear(value);
                    }else if(i == 10){
                        excelDTO.setTenthYear(value);
                    }else if(i == 11){
                        excelDTO.setEleventhYear(value);
                    }else if(i == 12){
                        excelDTO.setTwelfthYear(value);
                    }else if(i == 13){
                        excelDTO.setThirteenthYear(value);
                    }else if(i == 14){
                        excelDTO.setFourteenthYear(value);
                    }else if(i == 15){
                        excelDTO.setFifteenthYear(value);
                    }else if(i == 16){
                        excelDTO.setSixteenthYear(value);
                    }else if(i == 17){
                        excelDTO.setSeventeenthYear(value);
                    }else if(i == 18){
                        excelDTO.setEighteenthYear(value);
                    }else if(i == 19){
                        excelDTO.setNineteenthYear(value);
                    }else if(i == 20){
                        excelDTO.setTwentiethYear(value);
                    }
                }
            }
            resultList.add(excelDTO);
        }
        return resultList;
    }

    public String getExcelValue(String type,BatchCommonData batchCommonData){
        String value = "";
        if(type.equals("原油价格（元/吨）")){
            value = batchCommonData.getOilPrice() == null ? "" : batchCommonData.getOilPrice().toString();
        }else if(type.equals("天然气价格（元/千方）")){
            value = batchCommonData.getGasPrice() == null ? "" : batchCommonData.getGasPrice().toString();
        }else if(type.equals("轻烃价格（元/吨）")){
            value = batchCommonData.getCondensatePrice() == null ? "" : batchCommonData.getCondensatePrice().toString();
        }else if(type.equals("液化气价格（元/吨）")){
            value = batchCommonData.getLiquidGasPrice() == null ? "" : batchCommonData.getLiquidGasPrice().toString();
        }else if(type.equals("原油商品率（%）")){
            value = batchCommonData.getOilCommodityRate() == null ? "" : batchCommonData.getOilCommodityRate().toString();
        }else if(type.equals("天然气商品率（%）")){
            value = batchCommonData.getGasCommodityRate() == null ? "" : batchCommonData.getGasCommodityRate().toString();
        }else if(type.equals("其他产品商品率（%）")){
            value = batchCommonData.getOtherCommodityRate() == null ? "" : batchCommonData.getOtherCommodityRate().toString();
        }
        return value;
    }

    @Override
    public String getName() {
        return "batch-common-data";
    }

    @Override
    public ServiceResult handleBatchDelete(String batchId) {
        return deleteByBatchId(batchId);
    }
}
